/********************************************
 * 功能说明: 
 * 模块名称: 
 * 系统名称: 
 * 软件版权: 北京银杉金服科技有限公司
 * 系统版本: 1.0.0
 * 开发人员: zhangfb
 * 开发时间: 2018/12/22 17:18
 * 审核人员: 
 * 相关文档: 
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.hyacinth.dubbo.io.netty.server.handler;

import com.hyacinth.dubbo.io.netty.protocol.request.LoginRequestPacket;
import com.hyacinth.dubbo.io.netty.protocol.response.LoginResponsePacket;
import com.hyacinth.dubbo.io.netty.session.Session;
import com.hyacinth.dubbo.io.netty.util.IDGenUtil;
import com.hyacinth.dubbo.io.netty.util.SessionUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.Date;
import java.util.UUID;

/**
 * 登录请求处理器
 * @author zhangfb
 * @version 1.0.0.1
 * @since JDK 1.8
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@ChannelHandler.Sharable
public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestPacket> {

    public static final LoginRequestHandler INSTANCE = new LoginRequestHandler();

    @Override
    protected void channelRead0(ChannelHandlerContext context, LoginRequestPacket loginRequestPacket) throws Exception {
        LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
        loginResponsePacket.setVersion(loginRequestPacket.getVersion());
        loginResponsePacket.setUsername(loginRequestPacket.getUsername());

        if (validLogin(loginRequestPacket)) {
            loginResponsePacket.setSuccess(true);
            String userId = IDGenUtil.randomId();
            loginResponsePacket.setUserId(userId);
            SessionUtil.bindSession(new Session(userId, loginRequestPacket.getUsername()), context.channel());
            System.out.println("[" + loginRequestPacket.getUsername() + "|" + userId +"]" + ": 登录成功");
        } else {
            loginResponsePacket.setReason("账号密码校验失败");
            loginResponsePacket.setSuccess(false);
            System.out.println(new Date() + ":[" + loginRequestPacket.getUsername() + "]" + ": 登录失败!");
        }

        // 登录响应
        context.channel().writeAndFlush(loginResponsePacket);
    }

    private boolean validLogin(LoginRequestPacket loginRequestPacket) {
        return "6012328".equals(loginRequestPacket.getPassword());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        SessionUtil.unBindSession(ctx.channel());
    }
}
